package cn.edu.gsau.info.util;

import cn.edu.gsau.info.exception.BusinessException;
import cn.edu.gsau.info.models.Code;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Data
public class UploadUtil implements Serializable {
    /*
     * @description:
     * @author: sjw
     * @date:
     * @param:
     * @return: 返回保存后的文件相对路径
     **/


    public Map<String,String> filedUpload(MultipartFile file ,String gonghao,String path) {
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //截取字符串
        String lastName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //得到新文件名
        String filename = UUID.randomUUID().toString() + lastName;
        //String realPath = req.getServletContext().getRealPath("/upload/"+gonghao) ;
        //设置文件存放路径
        String realPath = path+"/"+gonghao;
        //创建文件存放路径
        File filepath = new File(realPath);
        if (!filepath.exists()) {
            filepath.mkdirs();
        }
        try {
            file.transferTo(new File(filepath , filename));
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(Code.BUSINESS_EXCEPTION,"上传文件失败");
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("oldfilename",originalFilename);
        map.put("newfilename",filename);
        return map;
    }
}
